package com.aynu.gulimall.product.service.impl;

import com.aynu.gulimall.product.config.MyThreadPoolConfig;
import com.aynu.gulimall.product.entity.SkuImagesEntity;
import com.aynu.gulimall.product.entity.SpuInfoDescEntity;
import com.aynu.gulimall.product.entity.SpuInfoEntity;
import com.aynu.gulimall.product.service.*;
import com.aynu.gulimall.product.vo.SkuItemSaleAttrVo;
import com.aynu.gulimall.product.vo.SkuItemVo;
import com.aynu.gulimall.product.vo.SpuInfoGroupAttrVo;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.product.dao.SkuInfoDao;
import com.aynu.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
@Slf4j
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        /*key:
        catelogId: 0
        brandId: 0
        min: 0
        max: 0*/
        String key = (String) params.get("key");
        if (!StringUtils.isEmptyOrWhitespaceOnly(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmptyOrWhitespaceOnly(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmptyOrWhitespaceOnly(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {

            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skus = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skus;
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo itemVo = new SkuItemVo();

        //开启异步编排
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku的基本信息
            SkuInfoEntity skuInfoEntity = getById(skuId);
            itemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取spu销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            itemVo.setSaleAttrs(saleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取spu的介绍
            log.info("根据spuId={}，查询spu信息", res.getSpuId());
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            itemVo.setDesp(spuInfoDescEntity);
        }, threadPoolExecutor);

        CompletableFuture<Void> attrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取spu的规格参数信息
            List<SpuInfoGroupAttrVo> attrGroupVo =
                    attrGroupService.getAttrGroupWithAttrsBySpuId(res.getCatalogId(), res.getSpuId());
            itemVo.setGroupAttrs(attrGroupVo);
        }, threadPoolExecutor);

        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            //2、sku图片信息
            log.info("根据skuid={}，sku的图片信息", skuId);
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.getImageBuSkuId(skuId);
            itemVo.setImages(skuImagesEntityList);
        }, threadPoolExecutor);

        //等待所有的任务完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(imgFuture, attrFuture, descFuture, saleFuture, infoFuture);
        try {
            allOf.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return itemVo;
    }

}